import code.DBGenerator;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.XmlDocument;
import cucumber.api.java.en_scouse.An;
import org.sqlite.core.DB;
import ui.DBDialog;
import utils.AndroidFileUtils;
import utils.ParseEntryUtils;
import utils.PluginUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DatabaseGeneratorAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 获取 Project
        Project project = e.getData(PlatformDataKeys.PROJECT);
        PsiFile file = e.getData(PlatformDataKeys.PSI_FILE);
        PsiClass clazz = PluginUtils.getFileClass(file);
        DBDialog dialog = new DBDialog(clazz);
        dialog.setOnGenerateListener((fields, priKeyField) -> {
            // 注意：生成代码与创建文件必须要在子线程中执行
            WriteCommandAction.runWriteCommandAction(project, () -> {
                // 获取db目录
                VirtualFile dbDir = AndroidFileUtils.getDbFile(project);
                // 获取当前正在编辑类的的所有成员遍历集合
                Object[] objects = ParseEntryUtils.parseEntry(e);
                if (objects == null || objects.length != 3) {
                    return;
                }
                PsiClass psiClass = (PsiClass) objects[0];
                String entryPackageName = (String) objects[1];
                // 没有界面时默认全选
//                Map<String, String> map = (Map<String, String>) objects[2];

                // 有界面时选择的属性
                Map<String, String> map = parseFields(fields);

                if (psiClass == null || map == null || map.size() == 0) {
                    return;
                }

                DBGenerator.generatorDbHelperFile(project, psiClass, map,
                        priKeyField, dbDir);
                DBGenerator.generatorDaoCodeFile(project, psiClass, entryPackageName, map, priKeyField, dbDir);
            });
        });
        dialog.pack();
        dialog.setVisible(true);
    }

    private Map<String, String> parseFields(ArrayList<PsiField> fields) {
        Map<String,String> map = new HashMap<>();
        for (PsiField p : fields) {
            // 成员变量的类型
            String type = p.getType().getPresentableText();
            // 成员变量的名称
            String name = p.getName();
            map.put(name, type);
        }
        return map;
    }
}
